package com.daom.websocket;

import com.daom.dao.MessageDao;
import com.daom.entity.Message;
import com.daom.entity.UserData;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.management.modelmbean.ModelMBean;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiaodao
 * date: 2019/8/19
 */
@Component
public class MessageHandler extends TextWebSocketHandler {

	@Autowired
	private MessageDao messageDaoImpl;

	private static final ObjectMapper MAPPER = new ObjectMapper();
	private static final Map<Long, WebSocketSession> SESSIONS = new HashMap<>();

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		Long uid = (Long) session.getAttributes().get("uid");
// 将当前用户的session放置到map中，后面会使用相应的session通信
		SESSIONS.put(uid, session);
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {

		Long uid = (Long) session.getAttributes().get("uid");
		JsonNode jsonNode = MAPPER.readTree(textMessage.getPayload());
		Long toId = jsonNode.get("toId").asLong();
		String msg = jsonNode.get("msg").asText();
		//获取用户对象
		Message build = Message.builder().from(UserData.USER_MAP.get(uid))
			.to(UserData.USER_MAP.get(toId))
			.msg(msg).build();

		//save
		messageDaoImpl.saveMessage(build);
		// 判断to用户是否在线
		WebSocketSession toSession = SESSIONS.get(toId);
		if (toSession != null && toSession.isOpen()) {
			//TODO 具体格式需要和前端对接
			toSession.sendMessage(new TextMessage(MAPPER.writeValueAsString(build)));
			// 更新消息状态为已读
			this.messageDaoImpl.updateMessageState(build.getId(), 2);
		}
	}

	/**
	 * 断开连接移除id
	 * @param session
	 * @param status
	 * @throws Exception
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		Long uid = (Long)  session.getAttributes().get("uid");
		SESSIONS.remove(uid);
	}
}
